package com.ksyzt.ksite2.test;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import com.ksyzt.gwt.server.common.Thumbnail;
import com.ksyzt.gwt.server.common.Util;
import com.ksyzt.ksite2.server.common.Application;
import com.ksyzt.ksite2.server.database.dao.IATTACHMENTDAO;
import com.ksyzt.ksite2.server.database.dao.INEWSDAO;
import com.ksyzt.ksite2.server.database.dao.impl.ATTACHMENTDAOImpl;
import com.ksyzt.ksite2.server.database.dao.impl.NEWSDAOImpl;
import com.ksyzt.ksite2.shared.modle.ATTACHMENTObj;
import com.ksyzt.ksite2.shared.modle.NEWSObj;

public class ImportNewsData {

	public final String image_path = "d:\\init";

	public static void main(String[] args) throws IOException, SQLException {
		ImportNewsData app = new ImportNewsData();
		File f = new File(app.image_path);
		if (f.exists()) {
			f.delete();
			
		}
		f.mkdir();

		// app.prepare_picture();
		// app.import_dynamic();
		//app.import_images();
		
		app.import_emag();
	}

	/**
	 * 电子杂志
	 * @throws IOException 
	 * @throws SQLException 
	 */
	private void import_emag() throws IOException, SQLException {
		
		INEWSDAO
		 dao =new NEWSDAOImpl(Application.getConnection());
		
		IATTACHMENTDAO daoa=new ATTACHMENTDAOImpl(Application.getConnection());
		
		String path="D:\\360Downloads\\新闻中心\\新闻中心\\电子刊物\\";
		String str="2013年简报";
		File root = new File(path+str);
		File[] fs = root.listFiles(new FilenameFilter() {
			
			@Override
			public boolean accept(File dir, String name) {
				// TODO Auto-generated method stub
				if(name.endsWith(".doc"))
					return true;
				return false;
			}
		});

		for (File f : fs) {
			String name=f.getName();
			String fn=Util.randomString(8)+".doc";
			Util.copyFile(f.getAbsolutePath(), "d:\\doc\\"+fn);
			NEWSObj news=new NEWSObj();
			news.setTITLE(str+"-"+name.substring(0,name.lastIndexOf(".")));
			
			news.setCONTENT(news.getTITLE());
			news.setADDTIME(Util.getCurrentSQLTimestamp());
			news.setAUTHOR("大藤峡通讯员");
			news.setDISPLAY(1);
			news.setLASTED(0);
			news.setTAG("");
			news.setOID(25);
			news.setORIGION("大藤峡");
			news.setVIEWER(0);
			news.setUSERID(1);
			news.setUPTOP(0);
			news.setUPDATETIME(news.getADDTIME());
			news.setSUMMARY(news.getTITLE());
			dao.insertObject(news);
			
			ATTACHMENTObj at=new ATTACHMENTObj();
			at.setCDATE(Util.getCurrentSQLTimestamp());
			at.setDCOUNT(0);
			at.setDREQUIRE(0);
			at.setTITLE(news.getTITLE());
			at.setFTYPE("application/msword");
			at.setFILEPATH("upload/init/"+fn);
			at.setNID("NEWS"+news.getID());
			at.setTAG(Util.randomString(12));
			daoa.insertObject(at);
			
			System.out.println("export>" + news.getTITLE());
			
		}
	}

	private void import_images() throws IOException, SQLException {
		String path = "D:\\360Downloads\\新闻中心\\新闻中心\\图片新闻";

		File root = new File(path);
		File[] fs = root.listFiles();

		for (File f : fs) {
			if (f.isDirectory()) {
				parseImages(f);
			}
		}
	}

	private void parseImages(File f) throws IOException, SQLException {
		INEWSDAO dao = new NEWSDAOImpl(Application.getConnection());
		File[] fs = f.listFiles();

		File[] imgs = f.listFiles(new FilenameFilter() {

			@Override
			public boolean accept(File dir, String name) {
				if (name.endsWith(".jpeg"))
					return true;
				return false;
			}
		});

		String name = f.getAbsolutePath();
		String date = f.getName().substring(0, 8);

		System.out.println(date);
		int year = Integer.valueOf(date.substring(0, 4));
		int month = Integer.valueOf(date.substring(4, 6));
		int day = Integer.valueOf(date.substring(6, 8));

		Date d = new Date();
		d.setYear(year - 1900);
		d.setMonth(month - 1);
		d.setDate(day);
		System.out.println(d);
		int lastpos=name.lastIndexOf("\\");
		String title = name.substring(lastpos+10);

		Map<File, String> imagemap = new HashMap<File, String>();
		String[] pics = { "一", "二", "三", "四", "五", "六", "七", "八", "九", "十", };
		int index = 0;
		for (File img : imgs) {
			String n = Util.randomString(8) + ".jpg";
			String fn = image_path + "\\" + n;
			String web = "upload/init/" + n;
			Util.copyFile(img.getAbsolutePath(), fn);
			String thmnbfilename = fn.substring(0, fn.lastIndexOf("."))
					+ "_s.jpg";
			Thumbnail thumb = new Thumbnail(fn, thmnbfilename);
			thumb.resize(140, 115);

			imagemap.put(img, web);

			NEWSObj news = new NEWSObj();

			news.setTITLE(title + "(" + pics[index++] + ")");

			news.setCONTENT(news.getTITLE());
			news.setADDTIME(new Timestamp(d.getTime()));
			news.setAUTHOR("大藤峡通讯员");
			news.setDISPLAY(1);
			news.setLASTED(0);
			news.setTAG("");
			news.setOID(17);
			news.setORIGION("大藤峡");
			news.setVIEWER(0);
			news.setUSERID(1);
			news.setUPTOP(0);
			news.setUPDATETIME(news.getADDTIME());
			news.setSUMMARY(news.getTITLE());
			news.setICON(web);
			dao.insertObject(news);
			System.out.println("export>" + news.getTITLE());
		}

		for (File f1 : f.listFiles()) {
			if (f1.isDirectory()) {
				parseImages(f1);
			}
		}

	}

	/**
	 * 倒入新闻动态
	 * 
	 * @throws IOException
	 * @throws SQLException
	 */
	public void import_dynamic() throws IOException, SQLException {
		String path = "D:\\360Downloads\\新闻中心\\新闻中心\\公司动态";

		File root = new File(path);
		File[] fs = root.listFiles();

		for (File f : fs) {
			if (f.isDirectory()) {
				importDirectory(f);
			}
		}
	}

	private void importDirectory(File f) throws IOException, SQLException {

		INEWSDAO dao = new NEWSDAOImpl(Application.getConnection());
		File[] fs = f.listFiles();
		NEWSObj news = new NEWSObj();

		File[] imgs = f.listFiles(new FilenameFilter() {

			@Override
			public boolean accept(File dir, String name) {
				if (name.endsWith(".jpeg"))
					return true;
				return false;
			}
		});

		Map<File, String> imagemap = new HashMap<File, String>();

		for (File img : imgs) {
			String n = Util.randomDigital(8) + ".jpg";
			String fn = image_path + "\\" + n;
			String web = "upload/init/" + n;
			Util.copyFile(img.getAbsolutePath(), fn);
			String thmnbfilename = fn.substring(0, fn.lastIndexOf("."))
					+ "_s.jpg";
			Thumbnail thumb = new Thumbnail(fn, thmnbfilename);
			thumb.resize(140, 115);

			imagemap.put(img, web);
		}
		for (File f0 : fs) {
			if (f0.isDirectory()) {
				importDirectory(f0);
			} else {
				String filetype = "";
				String name = f0.getAbsolutePath();
				System.out.println(name);
				int index = name.lastIndexOf(".");
				if (index > 0) {
					filetype = name.substring(index + 1);
					filetype = filetype.toLowerCase();

					if (filetype.equals("jpeg")) {
						// 处理图片
						String source = f0.getAbsolutePath();
					} else if (filetype.equals("txt")) {
						// 处理文本
						// StringBuilder sb = new StringBuilder();

						String text = readTextFile(f0);
						int pos = 0;
						pos = text.indexOf("\r\n");
						if (pos > 0) {
							pos = text.indexOf("\r\n", pos + 2);
						}

						if (pos > 0) {
							String date = f.getName().substring(0, 8);

							System.out.println(date);
							int year = Integer.valueOf(date.substring(0, 4));
							int month = Integer.valueOf(date.substring(4, 6));
							int day = Integer.valueOf(date.substring(6, 8));

							Date d = new Date();
							d.setYear(year - 1900);
							d.setMonth(month - 1);
							d.setDate(day);
							System.out.println(d);

							String pics = "";
							int imgindex = 0;
							for (File f1 : imagemap.keySet()) {
								if (imgindex == 0) {
									news.setICON(imagemap.get(f1));
								} else {
									pics = "<div style='text-align:center;'><img  class='article_image' src='"
											+ imagemap.get(f1) + "' /></div>";
								}
								imgindex++;
							}

							String title = text.substring(9, pos);
							title = title.replaceAll("\r\n", "");
							news.setTITLE(title);

							String content = text.substring(pos);

							int p = content.lastIndexOf("\r\n",
									content.length());
							p = content.lastIndexOf("\r\n", p);
							p = content.lastIndexOf("\r\n", p);
							if (p > 0) {

								String c = content.substring(0, p);
								c = c.replace("\r\n", "<p>");
								String last = content.substring(p);
								last = last.replace("\r\n", "");
								last = "<div style='align:right'>" + last
										+ "</div>";

								news.setCONTENT(pics + c + last);
							}

							news.setADDTIME(new Timestamp(d.getTime()));
							news.setAUTHOR("大藤峡通讯员");
							news.setDISPLAY(1);
							news.setLASTED(0);
							news.setTAG("");
							news.setOID(18);
							news.setORIGION("大藤峡");
							news.setVIEWER(0);
							news.setUSERID(1);
							news.setUPTOP(0);
							news.setUPDATETIME(news.getADDTIME());
							news.setSUMMARY(news.getTITLE());

							System.out.println(news.toXMLString(null));
							dao.insertObject(news);

						}
					}
				}
			}
		}
	}

	public void prepare_picture() throws IOException {
		String path = "D:\\360Downloads\\新闻中心\\新闻中心\\图片新闻";

		File root = new File(path);
		File[] fs = root.listFiles();

		for (File f : fs) {
			if (f.isDirectory()) {
				parseDirectory(f);
			}
		}

	}

	private void parseDirectory(File f) throws IOException {
		File[] fs = f.listFiles();

		for (File f0 : fs) {
			if (f0.isDirectory()) {
				parseDirectory(f0);
			} else {
				String filetype = "";
				String name = f0.getAbsolutePath();
				int index = name.lastIndexOf(".");
				if (index > 0) {
					filetype = name.substring(index + 1);
					filetype = filetype.toLowerCase();

					if (filetype.equals("jpg")) {
						String source = f0.getAbsolutePath();
						String target = f0.getAbsolutePath()
								.substring(0, index) + ".jpeg";
						Thumbnail nail = new Thumbnail(source, target);
						nail.resizeByWidth(800);
						System.out.println(target);
					}
				}
			}
		}
	}

	public static String readTextFile(File source) throws IOException {

		String text = "";
		BufferedReader br;
		InputStreamReader isr = new InputStreamReader(new FileInputStream(
				source), "GB2312");
		br = new BufferedReader(isr);
		String data = br.readLine();// 一次读入一行，直到读入null为文件结束
		while (data != null) {
			text += data;
			text += "\r\n";
			data = br.readLine(); // 接着读下一行
		}
		br.close();

		return text;
	}
}
